import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { connect } from 'react-redux';
import { Row, Col, Checkbox, Form, Input, Select, Button } from 'antd';
const Option = Select.Option;
const FormItem = Form.Item;
import dataCenter from '../../dataCenter';
// import {
// 	this.props.updateDetail
// } from '../../action';
const styles = {
	wrapper: {
    height: '100%',
    background: 'rgb(243, 245, 246)',
    width: 400,
    minWidth: 400,
    overflow: 'auto'
	},
	wrapperView: {
		display: ''
	},
	selectedDirection: {
		border: '1px solid #ddd',
		background: '#fff',
		fontSize: 22,
		cursor: 'pointer'
	},
	defaultDirection: {
		fontSize: 22,
		cursor: 'pointer'
	}
}

class PropertyEditor extends Component {
	constructor(props) {
		super(props);
		const renderObj = (props.formType === 'node' ? props.dealNodes.find(item => item.selected) : props.dealRelations.find(item => item.selected)) || {};
		console.log('renderObj: ', renderObj)
		this.state = {
			labels: [],
			alias: renderObj.alias || '',
			label: renderObj.label || '',
			type: renderObj.type || '',
			direction: renderObj.direction || '',
			leftNode: '',
			rightNode: '',
			propsObj: renderObj.props || {},
			conditionArray: renderObj.criteria || [],
			propValue: '',
			prop: '',
			operator: '',
			leftPropertiy: '',
			rightPropertiy: ''
		};
		this.getPropertyEditorState = this.getPropertyEditorState.bind(this);
	}
	static defaultProps = {
		formType: ''
	}
	componentDidMount() {
		dataCenter.getLabels().then(labels => {
			this.setState({
				labels
			})
		});
	}
	getPropertyEditorState() {
		return this.state;
	}
	handleChangeSelect = (type, value) => {
		const { dealRelations, dealNodes, formType, createdNodesList } = this.props;
		if (formType == 'relation') {
			this.props.dispatch(this.props.updateDetail(formType, {key: type, value: value}));
		} else {
			if (type === 'label') {
			  this.props.dispatch(this.props.getNode(createdNodesList.find(item => item.label === value).id));
			}
			this.setState({
				[type]: value
			})
		}
		// this.props.dispatch(this.props.updateDetail(formType, {key: type, value: value}));
	}
	changeNode = (type, value) => {
		this.setState({
			[type]: value
		})
	}
	changeLeftProperty = (type, value) => {
		this.setState({
			[type]: value
		})
	}
	changeOperator = (type, value) => {
		this.setState({
			[type]: value
		})
	}
	handleChange = (type, e) => {
		this.setState({
			[type]: e.target.value
		})
	}
	handleChangeProp = (type, value) => {
		this.setState({
			[type]: value
		})
	}
	newNode = () => {
		this.props.dispatch(this.props.updateDetail('node', {key: 'label', value: this.state.label}));
		this.props.dispatch(this.props.updateDetail('node', {key: 'alias', value: this.state.alias}));
	}
	addCondition = () => {
		const { operator, leftNode, rightNode, leftPropertiy, rightPropertiy, conditionArray } = this.state;
		if (operator && leftNode && rightNode && leftPropertiy && rightPropertiy) {
			this.setState({
				conditionArray: [
					...this.state.conditionArray,
					[`${leftNode}.${leftPropertiy}`, operator, `${rightNode}.${rightPropertiy}`]
				],
				operator: '',
				leftNode: '',
				rightNode: '',
				leftPropertiy: '',
				rightPropertiy: ''
			}, () => {
				this.props.dispatch(this.props.updateDetail('relation', {key: 'criteria', value: this.state.conditionArray}));
				ReactDOM.findDOMNode(this.refs.propertyEditor).scrollTo(0, ReactDOM.findDOMNode(this.refs.propertyEditor).scrollHeight);
			})
		}
	}
	deleteCondition = (index) => {
		this.setState({
			conditionArray: [...this.state.conditionArray.slice(0, index), ...this.state.conditionArray.slice(index + 1)]
		}, () => {
			this.props.dispatch(this.props.updateDetail('relation', {key: 'criteria', value: this.state.conditionArray}));
		})
	}
	newProp = () => {
		const {propsObj, propValue, prop} = this.state;
		if (propValue && prop) {
			this.setState({
				propsObj: Object.assign(this.state.propsObj, {[propValue]: prop}),
				propValue: '',
				prop: ''
			}, () => {
				this.props.dispatch(this.props.updateDetail('relation', {key: 'props', value: this.state.propsObj}));
			})
		}
	}
	deleteProp = (item) => {
		delete this.state.propsObj[item];
		this.setState({
			propsObj: this.state.propsObj
		}, () => {
			this.props.dispatch(this.props.updateDetail('relation', {key: 'props', value: this.state.propsObj}));
		})
	}
	changeInput = (type, e) => {
		const value = e.target.value;
		const { dealRelations, dealNodes, formType } = this.props;
		this.setState({
			[type]: value
		}, () => {
			if (formType == 'relation') {
				this.props.dispatch(this.props.updateDetail(formType, {key: type, value: this.state[type]}));
			}
		})
	}
	chooseDirection = (direction) => {
		this.setState({
			direction
		}, () => {
			this.props.dispatch(this.props.updateDetail('relation', {key: 'direction', value: direction}));
		})
	}
	render() {
		const {alias, label, type, direction, leftNode, rightNode, leftPropertiy, operator, rightPropertiy, propsObj, conditionArray, propValue, prop} = this.state;
		const { originFields, handleType, formType, dealRelations, dealNodes } = this.props;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
    };
    const renderObj = (formType === 'node' ? dealNodes.find(item => item.selected) : dealRelations.find(item => item.selected)) || {};
    const startNode = dealNodes.find(item => item.id === (renderObj && renderObj.associateNode && renderObj.associateNode[0] && renderObj.associateNode[0].id));
    const endNode = dealNodes.find(item => item.id === (renderObj && renderObj.associateNode && renderObj.associateNode[1] && renderObj.associateNode[1].id));
		const newNodes = dealNodes.filter(item => item.alias);
		const propertyChoices = newNodes.reduce((pre, item) => {
			return _.uniq([...pre, ...Object.keys(item.columns).map(v => (item.alias + '.' + v))])
		}, []);
		const leftProperties = newNodes.find(item => item.alias === leftNode) && Object.keys(newNodes.find(item => item.alias === leftNode).columns);
		const rightProperties = newNodes.find(item => item.alias === rightNode) && Object.keys(newNodes.find(item => item.alias === rightNode).columns);
		return (
			<div style={!formType ? styles.wrapperView : styles.wrapper} ref="propertyEditor" className="thin-scrollbar">
				{
					formType === 'node' || formType === 'relation' ?
					<Form>
						<Row style={{margin: 30, fontSize: 15, fontWeight: 'bold'}}>
							基本信息
						</Row>
						<FormItem {...formItemLayout} label="别名">
	            <Input placeholder="别名" style={{ width: '100%' }} value={alias} onChange={this.changeInput.bind(null, 'alias')}/>
	          </FormItem>
	          {
	          	formType === 'node' ?
	          	<FormItem {...formItemLayout} label="标签">
			          <Select style={{ width: '100%' }} placeholder="标签" value={label} onChange={this.handleChangeSelect.bind(null, 'label')}>
		          		{this.props.createdNodesList.map(item => <Option key={item.label} label={item.label}>{item.label}</Option>)}
		          	</Select>
		          </FormItem>
		          :
		          <FormItem {...formItemLayout} label="类型">
		            <Input placeholder="类型" style={{ width: '100%' }} value={type} onChange={this.changeInput.bind(null, 'type')}/>
		          </FormItem>
	          }
	          {
	          	formType === 'relation' ?
	          	<FormItem style={{marginBottom: 10}} {...formItemLayout} label="属性">
	          		<Input placeholder="属性" value={propValue} onChange={this.handleChange.bind(null, 'propValue')}/>
		          </FormItem>
		          :
		          null
	          }
	          {
	          	formType === 'relation' ?
	          	<Row>
		          	<Col offset={6} span={16}>
		          		<Select style={{ width: '100%' }} value={prop} onChange={this.handleChangeProp.bind(null, 'prop')}>
			          		{propertyChoices.map(item => <Option key={item} label={item}>{item}</Option>)}
			          	</Select>
		          	</Col>
		          </Row>
		          :
		          null
	          }
	          {
	          	formType === 'relation' ?
	          	<Row style={{height: 55}}>
		          	<Col offset={6} span={16}>
		          		<Button type="primary" style={{position: 'absolute', right: 0, top: 5}} size='large' onClick={this.newProp}>确定</Button>
		          	</Col>
		          </Row>
		          :
		          null
	          }
	          {
	          	formType === 'relation' ?
	          	<div>
	          	{
	          		Object.keys(propsObj).map((item, index) => {
	          			return (
	          				<FormItem style={{marginBottom: 8}} key={index} {...formItemLayout} label={`${item}`}>
					            <Input style={{width: 230}} disabled value={propsObj[item]}/>
			          			<i style={{position: 'absolute', right: 0, cursor: 'pointer'}} className="icon iconfont icon-speakermutecopy" onClick={this.deleteProp.bind(null, item)}></i>
					          </FormItem>
	          			)
		          	})
	          	}
		          </div>
		          :
		          null
	          }
	          {
	          	formType === 'node' ?
	          	null
	          	:
	          	<FormItem {...formItemLayout} label="左节点">
			          <label>{startNode && startNode.alias}</label>
		          </FormItem>
	          }
	          {
	          	formType === 'node' ?
	          	null
	          	:
	          	<FormItem {...formItemLayout} label="右节点">
			          <label>{endNode && endNode.alias}</label>
		          </FormItem>
	          }
	          {
	          	formType === 'node' ?
	          	<Row>
		          	<Col offset={6} span={16}>
		          		<Button type="primary" style={{position: 'absolute', right: 0}} size='large' onClick={this.newNode}>保存</Button>
		          	</Col>
		          </Row>
		          :
		          null
	          }
	          {
	          	formType === 'node' ?
	          	null
	          	:
	          	<FormItem {...formItemLayout} label="方向">
			          <i className="icon iconfont icon-xiangzuo" style={direction === 1 ? styles.selectedDirection : styles.defaultDirection} onClick={this.chooseDirection.bind(null, 1)}></i>
			          <i className="icon iconfont icon-xiangyou" style={{...(direction === 0 ? styles.selectedDirection : styles.defaultDirection) ,marginLeft: 35}} onClick={this.chooseDirection.bind(null, 0)}></i>
			          <i className="icon iconfont icon-shuangxiang" style={{...(direction === 2 ? styles.selectedDirection : styles.defaultDirection) ,marginLeft: 35}} onClick={this.chooseDirection.bind(null, 2)}></i>
		          </FormItem>
	          }
					</Form>
					:
					null
				}
				{
					formType === 'relation' ?
					<Form>
						<Row style={{margin: 30, fontSize: 15, fontWeight: 'bold'}}>
							添加条件
						</Row>
						<FormItem {...formItemLayout} label="左节点" style={{marginBottom: 10}}>
							<Select style={{ width: '100%' }} placeholder="左节点" value={leftNode} onChange={this.changeNode.bind(null, 'leftNode')}>
		        		{(newNodes || []).map(item => <Option key={item.alias} label={item.alias}>{item.alias}</Option>)}
		        	</Select>
	        	</FormItem>
	        	<FormItem {...formItemLayout} label="属性" style={{paddingLeft: 45}}>
							<Select style={{ width: '100%' }} placeholder="属性" value={leftPropertiy} onChange={this.changeLeftProperty.bind(null, 'leftPropertiy')}>
		        		{(leftProperties || []).map(item => <Option key={item} label={item}>{item}</Option>)}
		        	</Select>
	        	</FormItem>
	        	<FormItem {...formItemLayout} label="逻辑">
							<Select style={{ width: '100%' }} placeholder="逻辑" value={operator} onChange={this.changeOperator.bind(null, 'operator')}>
		        		{([{m: '=', v: '='}, {m: '<', v: '<'}, {m: '>', v: '>'}]).map(item => <Option key={item.v} label={item.v}>{item.v}</Option>)}
		        	</Select>
	        	</FormItem>
	        	<FormItem {...formItemLayout} label="右节点" style={{marginBottom: 10}}>
							<Select style={{ width: '100%' }} placeholder="右节点" value={rightNode} onChange={this.changeNode.bind(null, 'rightNode')}>
		        		{(newNodes || []).map(item => <Option key={item.alias} label={item.alias}>{item.alias}</Option>)}
		        	</Select>
	        	</FormItem>
	        	<FormItem {...formItemLayout} label="属性" style={{paddingLeft: 45}}>
							<Select style={{ width: '100%' }} placeholder="属性" value={rightPropertiy} onChange={this.changeLeftProperty.bind(null, 'rightPropertiy')}>
		        		{(rightProperties || []).map(item => <Option key={item} label={item}>{item}</Option>)}
		        	</Select>
	        	</FormItem>
	        	<Row style={{height: 55}}>
	          	<Col offset={6} span={16}>
	          		<Button type="primary" style={{position: 'absolute', right: 0}} size='large' onClick={this.addCondition}>添加</Button>
	          	</Col>
	          </Row>
					</Form>
					:
					null
				}
				{
					formType === 'relation' ?
					<div>
        	{
        		conditionArray.map((item, index) => {
        			return (
        				<FormItem style={{marginBottom: 8}} key={index} {...formItemLayout} label={`已添加条件${index + 1}`}>
			            <Input style={{width: 230, overflow: 'hidden'}} disabled value={`${item[0]} ${item[1]} ${item[2]}`}/>
	          			<i style={{position: 'absolute', right: 0, cursor: 'pointer'}} className="icon iconfont icon-speakermutecopy" onClick={this.deleteCondition.bind(null, index)}></i>
			          </FormItem>
        			)
          	})
        	}
          </div>
          :
          null
				}
			</div>
		)
	}
}

export default PropertyEditor;
